package com.huiminpay.merchant.service;

import com.huiminpay.common.cache.domain.CommonErrorCode;
import com.huiminpay.common.cache.exception.BusinessCast;
import com.huiminpay.common.cache.util.PhoneUtil;
import com.huiminpay.common.cache.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author: HWW
 * @Date: 2021/8/1817:41
 * @Desc:
 */
@Service
@Slf4j
public class SmsService{

    @Autowired
    private RestTemplate restTemplate;

    @Value("${sms.url}")
    private String smsUrl;

    @Value("${sms.effectiveTime}")
    private String effectiveTime;

    //发送短信服务
    public String sendSms(String phone){

        if(StringUtils.isEmpty(phone)){
            BusinessCast.cast(CommonErrorCode.E_100112);
        }

        if(!PhoneUtil.isMatches(phone)){
            BusinessCast.cast(CommonErrorCode.E_100109);
        }


        String url = smsUrl+"/generate?effectiveTime="+effectiveTime+"&name=sms";

        log.info("调用短信微服务发送验证码：url:{}", url);
        //请求体
        Map<String,Object> body = new HashMap<>();
        body.put("mobile", phone);
        //请求头
        HttpHeaders httpHeaders = new HttpHeaders();
        //设置数据格式————JSON
        httpHeaders.setContentType(MediaType.APPLICATION_JSON);
        //封装请求参数
        HttpEntity httpEntity = new HttpEntity<>(body, httpHeaders);

        try {
            ResponseEntity<Map> responseEntity = restTemplate.exchange(url, HttpMethod.POST, httpEntity, Map.class);
            Map responseBody = responseEntity.getBody();

            log.info("获取验证码：【{}】", responseBody);

            //取出body中的result数据
            if (responseBody == null || responseBody.get("result") == null) {
                throw new RuntimeException("发送验证码出错");
            }
            Map result = (Map)responseBody.get("result");
            String value = result.get("key").toString();

            return value;
        }catch (Exception e){
            e.printStackTrace();
            log.error("");
            BusinessCast.cast(CommonErrorCode.E_100109);
            return null;
        }

    }
}
